package com.spring.component.test.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @ClassName: SocketServer
 * @Description:
 * @author: liushihua
 * @date: 2018/11/29
 **/
public class SocketServer {
	public static final int PORT = 5000;

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		ServerSocket server = null;
		try {
			server = new ServerSocket(PORT);
			Socket socket;
			InputStream is;
			OutputStream os;
			System.out.println("start server...");
			while (true) {
				socket = server.accept();
				String clientIp = socket.getInetAddress().getHostAddress();
				System.out.println("client [" + clientIp + "] connected");

				is = socket.getInputStream();
				os = socket.getOutputStream();

				byte[] bytes = new byte[1024];
				int len;
				while ((len = is.read(bytes)) != -1) {
					String message = new String(bytes, 0, len, "UTF-8");
					System.out.println("recvice message from [" + clientIp + "]: " + message);
					System.out.println("是否回复：");
					int i = scanner.nextInt();
					if (i == 1) {
						System.out.println("say hello");
						os.write("hello".getBytes("UTF-8"));
						os.flush();
					}
				}
				os.close();
				is.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (server != null) {
				try {
					server.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
